package com.jcx.ldzj.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcx.ldzj.dao.UserRoleRelationMapper;
import com.jcx.ldzj.entity.UserRoleRelation;
import com.jcx.ldzj.service.IUserRoleRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户角色关联表 服务实现类
 * </p>
 *
 * @author ld
 * @since 2021-07-19
 */
@Slf4j
@Service
public class UserRoleRelationServiceImpl extends ServiceImpl<UserRoleRelationMapper, UserRoleRelation> implements IUserRoleRelationService {


    /**
     * 这个选择增加事务，统一失败和成功
     * @param list 传进来的要么是角色id的集合，要么是用户id的集合
     * @param userId 用户id，与roleid互相之间只会传其中一个进来
     * @param roleId 角色id
     * @return
     */
    @Override
    @Transactional
    public boolean saveUserAndRoles( List<String> list,String userId,String roleId) {
        if(userId!=null){
            this.deleteByuserId(userId);
        }else{
            //修改关系的时候要附带重置菜单缓存数据
            this.deleteByroleId(roleId);
        }
        for (int i=0;list!=null&&i<list.size();i++){
                UserRoleRelation userRoleRelation=new UserRoleRelation();
                if(userId!=null){
                    userRoleRelation.setUserId(userId);
                    userRoleRelation.setRoleId(list.get(i));
                }else {
                    userRoleRelation.setRoleId(roleId);
                    userRoleRelation.setUserId(list.get(i));
                }
                this.save(userRoleRelation);
        }
        return true;
    }

    @Override
    public boolean deleteByuserId(String userId) {
        return this.baseMapper.deleteByuserId(userId);
    }

    @Override
    public boolean deleteByroleId(String roleId) {
        return this.baseMapper.deleteByroleId(roleId);
    }


    @Override
    public List<UserRoleRelation> getByuserId(String userId) {
        return this.baseMapper.getByuserId(userId);
    }

    @Override
    public List<UserRoleRelation> getByroleId(String roleId) {
        return this.baseMapper.getByroleId(roleId);
    }
}
